<template>
  <!-- 自定义标题栏 -->
<div class="main-div">
  <div class="title-bar">
    <div class="left-section">
      <img src="@/assets/icons/tray-1.png" alt="App Icon" class="app-icon" />
      <span class="app-title">{{username}}</span>
    </div>
    <div class="window-controls">
      <el-icon style="background-color: #ecc94b" @click="minimizeWindow"><Minus /></el-icon>
      <el-icon style="background-color: #48bb78" @click="toggleMaximizeWindow"><FullScreen /></el-icon>
      <el-icon style="background-color: #f56565" @click="closeWindow"><Close /></el-icon>
    </div>
  </div>


  <div class="main-container">
    <!-- 左侧导航栏 -->
    <nav class="sidebar">
      <div class="nav-item" v-for="item in navList" :key="item.name" @click="onNavClick(item)">
        <el-icon :size="24"><component :is="item.icon" /></el-icon>
      </div>
    </nav>

    <!-- 中间模块栏 -->
    <aside class="module-list">
      <router-view name="module" />
    </aside>

    <!-- 右侧主内容 -->
    <main class="content-view">
      <router-view name="content" />
    </main>
  </div>
</div>
</template>

<script setup>
import { ref,nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ChatDotSquare, User, Setting, UserFilled } from '@element-plus/icons-vue'
import { Minus, Close,FullScreen  } from '@element-plus/icons-vue';
import { onMounted } from 'vue';
import {useContactStore} from '@/stores/contacts'
import {useGroupStore} from '@/stores/group'
import {useFriendRequestStore} from '@/stores/friendRequest.js'
import {useFriendStore} from '@/stores/friendStore.js'
import { ElNotification } from 'element-plus';
import request from '@/axios/index'
const router = useRouter()
const username = ref();
const navList = ref([
  { name: 'chat', icon: ChatDotSquare, route: '/chat' },
  { name: 'contacts', icon: User, route: '/friend' },
  { name: 'group', icon: UserFilled, route: '/group' }, // ✅ 新增群聊导航
  { name: 'settings', icon: Setting, route: '/settings' },
])
const getChatRequest = ()=>{
  //获取聊天记录列表
  request.get('/chat-conversation/all').then((res)=>{
      // contactStore.initContacts(res);
      console.log("初始化时拿到聊天列表：",res);
      contactStore.initContacts(res);
    })
}

const onNavClick = (item) => {
  if(item.name === 'chat') getChatRequest();
  router.push(item.route)
}

const groupStore = useGroupStore()
const contactStore = useContactStore()
const friendRequestStore = useFriendRequestStore();
const friendStore = useFriendStore();
onMounted(()=>{
    window.electronAPI.getUsername().then((res)=>{
      username.value = res;
    })

    getChatRequest();



    window.electronAPI.socket.onMessage((msgStr)=>{
      const msgWrapper = msgStr;
      const contentObj = msgWrapper.content;
      console.log("contentObj",contentObj)
      if(msgWrapper.type === 1){
        const contact = contactStore.contacts.find(c=>c.name == contentObj.senderId);
        console.log("contact",contact)
        if(contact){
          contactStore.addMessage(contentObj);
          console.log("contactStore",contactStore.contacts)
          contactStore.setUnreadCount(contentObj.receiverId,1);
        }else{
          const now = Date.now().toString();
          contactStore.add({
            id : now,
            name: contentObj.senderId,
            avatar: 'https://picsum.photos/50/50',
            messages:[],
            unreadCount: 1,
          })
          createChat(contentObj.senderId,now);
          contactStore.addMessage(contentObj);
          contactStore.setUnreadCount(contentObj.senderId,1);
        }
      }else if(msgWrapper.type === 2){
        groupStore.sendMessage(contentObj.groupId,contentObj.senderId,contentObj.content,username.value);
      }else if(msgWrapper.type === 3){
        console.log("好友申请的监听消息:  ",contentObj);
        if(contentObj.receiverId == username.value)  {
          friendRequestStore.updateRequests(contentObj);
          console.log("好友仓库是否更新", friendRequestStore.friendRequest);
          // 显示成功通知
          ElNotification({
            title: '新的好友申请',
            message: `亲爱的 ${username.value}，${contentObj.senderId}发送给您一条好友申请！`,
            type: 'success',
            duration: 3000,
            customClass: 'friend-notification', // 添加自定义类
            position: 'top-right'
          });
        }
      }else if(msgWrapper.type === 6){
        console.log("通知给好友申请已通过",contentObj);
        if(contentObj.receiverId == username.value){
          friendStore.addFriend(contentObj); 
          const isRejected = contentObj.content.includes('拒绝');
          // 显示成功通知
          ElNotification({
            title: isRejected?'好友申请被拒绝':'好友申请已通过',
            message: `${contentObj.content}`,
            type: isRejected?'error':'success',
            duration: 3000,
            customClass: 'friend-notification', // 添加自定义类
            position: 'top-right'
          });
        }
      }else if(msgWrapper.type ===4){
        console.log("有表情来了",contentObj);
        if(contentObj.receiverId ==username.value){
          const contact = contactStore.contacts.find(c=>c.name == contentObj.senderId);
        console.log("contact",contact)
        if(contact){
          contactStore.addMessage(contentObj);
          console.log("contactStore",contactStore.contacts)
          contactStore.setUnreadCount(contentObj.receiverId,1);
        }else{
          const now = Date.now().toString();
          contactStore.add({
            id : now,
            name: contentObj.senderId,
            avatar: 'https://picsum.photos/50/50',
            messages:[],
            unreadCount: 1,
          })
          createChat(contentObj.senderId,now);
          contactStore.addMessage(contentObj);
          contactStore.setUnreadCount(contentObj.senderId,1);
        }
        }
      }
    })
})

const createChat = (friendName,id)=>{
    request.post('/chat-conversation/create',{
      friendId: friendName,
      orderNo: id,
    }).then((res)=>{
      console.log("创建聊天框成功：",res);
    })
}

// 自定义标题栏按钮操作
const minimizeWindow = () => {
  window.electronAPI?.ipcRenderer?.send('minimize-window');
};
const closeWindow = () => {
  window.electronAPI?.ipcRenderer?.send('close-window');
};
let isMaximized = false;

//最大化窗口
const toggleMaximizeWindow = () => {
  window.electronAPI?.ipcRenderer?.send('toggle-maximize');
  isMaximized = !isMaximized;
};

</script>


<style scoped>
.main-div{
  width: 100vw;
  height: 100vh;
}
.title-bar {
  height: 36px;
  width: 100%;
  background-color: #f8f9fa;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  -webkit-user-select: none;
  -webkit-app-region: drag;
  padding: 0 12px;
  border-bottom: 1px solid #ddd;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.left-section {
  display: flex;
  align-items: center;
}

.app-icon {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}

.app-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.window-controls {
  display: flex;
  align-items: center;
  -webkit-app-region: no-drag;
  gap: 12px; /* 加大间距 */
}

.window-controls .el-icon {
  font-size: 16px;
  background-color: #eaeaea;
  border-radius: 50%;
  padding: 6px;
  cursor: pointer;
  transition: background-color 0.2s, transform 0.2s;
}

.window-controls .el-icon:hover {
  background-color: #dcdcdc;
  transform: scale(1.1);
}

.window-controls .el-icon:active {
  background-color: #cfcfcf;
}



.main-container {
  display: flex;
  width: 100vw;
  height: calc(100vh - 36px); /* 减去标题栏高度 */
  overflow: hidden;
}

.sidebar {
  width: 64px;
  background-color: #2f2f2f;
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 10px;
}

.nav-item {
  margin: 20px 0;
  cursor: pointer;
}

.module-list {
  width: 260px;
  background-color: #f5f5f5;
  border-right: 1px solid #ddd;
  overflow-y: auto;
}

.content-view {
  flex: 1;
  background-color: white;
  height: 100%;
}

.friend-notification {
  .el-notification__title {
    font-weight: 600;
    color: #1e88e5;
  }
  .el-notification__content {
    font-size: 14px;
  }
}
</style>
